package com.plwf.lake.service.impl;

import com.plwf.lake.entity.LakeAdmin;
import com.plwf.lake.entity.Rule;
import com.plwf.lake.mapper.LakeAdminMapper;
import com.plwf.lake.mapper.RuleMapper;
import com.plwf.lake.service.LakeAdminService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

@Service
public class LakeAdminServiceImpl implements LakeAdminService{
    @Resource
    private LakeAdminMapper mapper;
    @Resource
    private RuleMapper dao;

    @Override
    public LakeAdmin get(LakeAdmin lakeAdmin) {
        return mapper.login(lakeAdmin);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=SQLException.class)
    public boolean save(LakeAdmin bean, List<Integer> powers) throws SQLException {
        boolean flag = true;
        if(bean.getId()!=null){
            if(this.mapper.update(bean)){
                if(this.dao.delete(bean.getId())){
                    int aid = bean.getId();
                    for(int pid : powers){
                        Rule rule = new Rule(aid,pid);
                        if(!dao.insert(rule)){
                            flag = false;
                            throw new SQLException("用户权限保存失败");
                        }
                    }
                }else{
                    flag = false;
                }
            }else{
                flag = false;
            }
        }else{
            if(this.mapper.insert(bean)){
                int aid = bean.getId();
                for(int pid : powers){
                    Rule rule = new Rule(aid,pid);
                    if(!dao.insert(rule)){
                        flag = false;
                        throw new SQLException("用户权限保存失败");
                    }
                }
            }else{
                flag = false;
            }
        }
        return flag;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=SQLException.class)
    public boolean remove(Integer id) {
        return this.mapper.delete(id);
    }

    @Override
    public List<LakeAdmin> find(Integer id) {
        return this.mapper.selectOne(id);
    }


    @Override
    public List<LakeAdmin> query() {
        return this.mapper.select();
    }

    @Override
    public LakeAdmin login(LakeAdmin bean) {
        return mapper.login(bean);
    }


}
